package com.mdp.tpa.pay.cm.service;

import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.service.SequenceService;
import com.mdp.core.utils.BaseUtils;
import com.mdp.core.utils.NumberUtil;
import com.mdp.micro.client.CallBizService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.tpa.pay.cm.entity.Orders;
import com.mdp.tpa.pay.cm.entity.UniOrder;
import com.mdp.tpa.pay.cm.client.AcPaymentPushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class OrdersService {

    @Value("${mdp.api-gate:http://gate}")
    String apiGate="";//http://localhost:7041

    @Autowired
    CallBizService callBizService;

    @Autowired
    SequenceService sequenceService;

    @Autowired
    AcPaymentPushService acPaymentPushService;

    @Autowired
    RedisTemplate redisTemplate;

    public Orders getOrdersById(String otype, String orderId) {
        Orders orders = new Orders();
        //0-电商商城商品，1-应用模块使用购买，2-vip购买会员，3-任务众包、推广活动费用等,4-服务商支付服务保障保证金
        if("1".equals(otype)) {
            //通过订单Id获取订单
            String url = String.format(apiGate + "/sys/sys/mo/moOrder/getOrderById?orderId=%s", orderId);
            Map<String,Object> result = callBizService.getForMap(url);
            //是否查询成功
            Tips impTips = (Tips) result.get("tips");
            if (!impTips.isOk()) {
                throw new BizException(impTips);
            }
            Map<String,Object> orderData = (Map<String, Object>) result.get("data");
            //设置订单参数
            orders.setId((String) orderData.get("id"));
            orders.setPayAt(new BigDecimal(Double.valueOf((Double) orderData.get("ofinalFee"))));
            orders.setUserid((String) orderData.get("ouserid"));
            orders.setOrderStatus((String) orderData.get("status"));
            orders.setPayStatus((String) orderData.get("sstatus"));
            orders.setPayId((String) orderData.get("payId"));
            orders.setPrepayId((String) orderData.get("prepayId"));
            orders.setRemarks((String) orderData.get("remark"));
            orders.setName((String) orderData.get("name"));
            orders.setOtype(otype);
        }else if("2".equals(otype)){
            UniOrder uniOrder=new UniOrder();
            uniOrder.setOtype(otype);
            uniOrder.setId(orderId);
            orders= this.getInterestsOrders(uniOrder);
        }else if("3".equals(otype)){
            //通过订单Id获取订单
            String url = String.format(apiGate + "/xm/xm/core/xmTaskOrder/getOrderById?orderId=%s", orderId);
            Map<String,Object> result = callBizService.getForMap(url);
            //是否查询成功
            Tips impTips = (Tips) result.get("tips");
            if (!impTips.isOk()) {
                throw new BizException(impTips);
            }
            Map<String,Object> orderData = (Map<String, Object>) result.get("data");
            //设置订单参数
            orders.setId((String) orderData.get("id"));
            orders.setPayAt(new BigDecimal(Double.valueOf((Double) orderData.get("finalFee"))));
            orders.setUserid((String) orderData.get("ouserid"));
            orders.setOrderStatus((String) orderData.get("ostatus"));
            orders.setPayStatus((String) orderData.get("payStatus"));
            orders.setPayId((String) orderData.get("payId"));
            orders.setPrepayId((String) orderData.get("prepayId"));
            orders.setRemarks((String) orderData.get("remark"));
            orders.setName((String) orderData.get("name"));
            orders.setOtype(otype);
        }else if("4".equals(otype)){//服务商保障金
            //通过订单Id获取订单
            String url = String.format(apiGate + "/sys/sys/guardOrder/getOrderById?id=%s", orderId);
            Map<String,Object> result = callBizService.getForMap(url);
            //是否查询成功
            Tips impTips = (Tips) result.get("tips");
            if (!impTips.isOk()) {
                throw new BizException(impTips);
            }
            Map<String,Object> orderData = (Map<String, Object>) result.get("data");
            //设置订单参数
            orders.setId((String) orderData.get("id"));
            orders.setPayAt(new BigDecimal(Double.valueOf((Double) orderData.get("ofinalFee"))));
            orders.setUserid((String) orderData.get("ouserid"));
            orders.setOrderStatus((String) orderData.get("status"));
            orders.setPayStatus((String) orderData.get("payStatus"));
            orders.setPayId((String) orderData.get("payId"));
            orders.setPrepayId((String) orderData.get("prepayId"));
            orders.setRemarks((String) orderData.get("remark"));
            orders.setName((String) orderData.get("name"));
            orders.setOtype(otype);
        }else if("7".equals(otype)){//投标直通车
            //通过订单Id获取订单
            String url = String.format(apiGate + "/xm/xm/core/xmTaskBidOrder/getOrderById?orderId=%s", orderId);
            Map<String,Object> result = callBizService.getForMap(url);
            //是否查询成功
            Tips impTips = (Tips) result.get("tips");
            if (!impTips.isOk()) {
                throw new BizException(impTips);
            }
            Map<String,Object> orderData = (Map<String, Object>) result.get("data");
            //设置订单参数
            orders.setId((String) orderData.get("id"));
            orders.setPayAt(new BigDecimal(Double.valueOf((Double) orderData.get("finalFee"))));
            orders.setUserid((String) orderData.get("ouserid"));
            orders.setOrderStatus((String) orderData.get("ostatus"));
            orders.setPayStatus((String) orderData.get("payStatus"));
            orders.setPayId((String) orderData.get("payId"));
            orders.setPrepayId((String) orderData.get("prepayId"));
            orders.setRemarks((String) orderData.get("remark"));
            orders.setName((String) orderData.get("name"));
            orders.setOtype(otype);
        }
        return orders;
    }

    public Orders getOrders(UniOrder order){
        if("2".equals(order.getOtype())){
            return this.getInterestsOrders(order);
        }else if("5".equals(order.getOtype())){
            return this.getRechargeOrders(order);
        }else {
            return this.getOrdersById(order.getOtype(),order.getId());
        }
    }

    /**
     * 创建充值订单
     * @param order
     * @return
     */
    public Orders getRechargeOrders(UniOrder order) {
        User user= LoginUtils.getCurrentUserInfo()  ;
        Orders orders=new Orders();
        orders.setOtype("5");
        orders.setUserid(user.getUserid() );
        orders.setUsername(user.getUsername());
        orders.setRemarks("充值"+order.getRechargeAt());
        orders.setName("充值"+order.getRechargeAt());
        orders.setPayStatus("0");
        orders.setOrderStatus("0");
        orders.setPayAt(order.getRechargeAt());
        if(!StringUtils.hasText(order.getId())){
            orders.setId(sequenceService.getTablePK("orders","id"));
        }else{
            orders.setId(order.getId());
        }
        return orders;
    }

    /**
     *
     * @param uniOrder
     * @return
     */
    public Orders getInterestsOrders(UniOrder uniOrder) {
        Orders orders = new Orders();
        //通过订单Id获取订单
        String url = String.format(apiGate + "/sys/sys/interestsOrders/detail?id=%s", uniOrder.getId());
        Map<String,Object> result = callBizService.getForMap(url);
        //是否查询成功
        Tips impTips = (Tips) result.get("tips");
        if (!impTips.isOk()) {
            throw new BizException(impTips);
        }
        Map<String,Object> orderData = (Map<String, Object>) result.get("data");
        if(orderData==null || orderData.isEmpty()){
            throw new BizException("orders-0","订单不存在");
        }
        //设置订单参数
        orders.setId((String) orderData.get("id"));
        orders.setPayAt(NumberUtil.getBigDecimal(orderData.get("finalFee")));
        orders.setUserid((String) orderData.get("userid"));
        orders.setOrderStatus((String) orderData.get("payStatus"));
        orders.setPayStatus((String) orderData.get("payStatus"));
        orders.setName( (String) orderData.get("name"));
        orders.setRemarks((String) orderData.get("remark"));
        orders.setOtype(uniOrder.getOtype());
        orders.setPayId((String)orderData.get("payId"));
        return orders;
    }


    public void payConfirm(String otype,String orderId,String payId, String tranId, BigDecimal payAt,String remarks) {
        redisTemplate.opsForValue().setIfAbsent("pay-notify-success-"+payId,"1",1, TimeUnit.HOURS);
        //0-电商商城商品，1-应用模块使用购买，2-vip购买会员
        if("1".equals(otype)) {
            //修改订单状态, 开通模块
            String url =  "/sys/sys/mo/moOrder/orderPaySuccess";
           Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","1","tranId",tranId,"payAt",payAt,"remarks",remarks));
            //是否查询成功
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("2".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/sys/sys/interestsOrders/payConfirm";
           Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","1","payAt",payAt,"tranId",tranId));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("3".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/xm/xm/core/xmTaskOrder/orderPaySuccess";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","1","payAt",payAt,"tranId",tranId));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("4".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/sys/sys/guardOrder/orderPaySuccess";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","1","payAt",payAt,"tranId",tranId));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("5".equals(otype)){
            //无须做任何动作
        }else if("7".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/xm/xm/core/xmTaskBidOrder/orderPaySuccess";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","1","payAt",payAt,"tranId",tranId));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }
        if("5".equals(otype)){
            acPaymentPushService.pushRechargeOrders(BaseUtils.map("id",orderId,"payId",payId,"payStatus","1","payAt",payAt,"tranId",tranId,"payTime",new Date(),"action","payNotify"));
        }else{
            acPaymentPushService.pushPaymentOrders(BaseUtils.map("id",orderId,"payId",payId,"payStatus","1","payAt",payAt,"tranId",tranId,"payTime",new Date(),"action","payNotify"));
        }

    }

    public void updatePrepayId(Orders ordersUpdate) {
        //0-电商商城商品，1-应用模块使用购买，2-vip购买会员
        if("1".equals(ordersUpdate.getOtype())) {
            String url =  "/sys/sys/mo/moOrder/updatePrepayId" ;
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",ordersUpdate.getId(),"payType",ordersUpdate.getPayType(),"prepayId",ordersUpdate.getPrepayId(),"payId",ordersUpdate.getPayId(),"payAt",ordersUpdate.getPayAt()));
            //是否查询成功
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("2".equals(ordersUpdate.getOtype())) {
            String url =  "/sys/sys/interestsOrders/updatePrepayId" ;
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",ordersUpdate.getId(),"payType",ordersUpdate.getPayType(),"prepayId",ordersUpdate.getPrepayId(),"payId",ordersUpdate.getPayId(),"payAt",ordersUpdate.getPayAt()));

            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("3".equals(ordersUpdate.getOtype())) {
            String url =  "/xm/xm/core/xmTaskOrder/updatePrepayId" ;
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",ordersUpdate.getId(),"payType",ordersUpdate.getPayType(),"prepayId",ordersUpdate.getPrepayId(),"payId",ordersUpdate.getPayId(),"payAt",ordersUpdate.getPayAt()));

            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("4".equals(ordersUpdate.getOtype())) {
            String url =  "/sys/sys/guardOrder/updatePrepayId" ;
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",ordersUpdate.getId(),"payType",ordersUpdate.getPayType(),"prepayId",ordersUpdate.getPrepayId(),"payId",ordersUpdate.getPayId(),"payAt",ordersUpdate.getPayAt()));

            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("7".equals(ordersUpdate.getOtype())) {
            String url =  "/xm/xm/core/xmTaskBidOrder/updatePrepayId" ;
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",ordersUpdate.getId(),"payType",ordersUpdate.getPayType(),"prepayId",ordersUpdate.getPrepayId(),"payId",ordersUpdate.getPayId(),"payAt",ordersUpdate.getPayAt()));

            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }
        //合并到createOrder中了，此处不再推送订单到ac财务系统
        //acPaymentPushService.pushOrders(BaseUtils.map("action","updatePrepayId","id",ordersUpdate.getId(),"prepayId",ordersUpdate.getPrepayId(),"payId",ordersUpdate.getPayId(),"payAt",ordersUpdate.getPayAt()));
    }

    /**
     * 超时未支付订单进行取消
     * @param otype
     * @param orderId
     * @param remarks
     */
    public void payCancel(String otype, String orderId,String payId, String remarks) {
        redisTemplate.opsForValue().setIfAbsent("pay-notify-cancel-"+payId,"1",1, TimeUnit.HOURS);
        //0-电商商城商品，1-应用模块使用购买，2-vip购买会员
        if("1".equals(otype)) {
            //修改订单状态, 开通模块
            String url =  "/sys/sys/mo/moOrder/payCancel";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","2","remarks",remarks));
            //是否查询成功
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("2".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/sys/sys/interestsOrders/payCancel";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","2","remarks",remarks));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("3".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/xm/xm/core/xmTaskOrder/payCancel";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","2","remarks",remarks));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("4".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/sys/sys/guardOrder/payCancel";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","2","remarks",remarks));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }else if("5".equals(otype)){
            //无须做任何动作
        }else if("7".equals(otype)){
            //修改订单状态, 开通模块
            String url =  "/xm/xm/core/xmTaskOrder/payCancel";
            Tips tips = callBizService.postForTips(url,BaseUtils.map("id",orderId,"payId",payId,"payStatus","2","remarks",remarks));
            if (!tips.isOk()) {
                throw new BizException(tips);
            }
        }
        if("5".equals(otype)){
            acPaymentPushService.pushRechargeOrders(BaseUtils.map("id",orderId,"payId",payId,"payStatus","2","remarks",remarks,"action","payNotify"));
        }else{
            acPaymentPushService.pushPaymentOrders(BaseUtils.map("id",orderId,"payId",payId,"payStatus","2","remarks",remarks, "action","payNotify"));
        }
    }
}
